package com.seven.controller;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.slf4j.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
public abstract class BaseController {

    public static final Logger LOGGER =LoggerFactory.getLogger(BaseController.class);
    /**
     * ThreadLocal确保高并发下每个请求的request，response都是独立的
     */
    private static ThreadLocal<ServletRequest> currentRequest = new ThreadLocal<ServletRequest>();
    private static ThreadLocal<ServletResponse> currentResponse = new ThreadLocal<ServletResponse>();
    private static ThreadLocal<HttpSession> currentSession = new ThreadLocal<HttpSession>();


    private static String LOGGER_LEVEL="LOGGER";

    @ModelAttribute
    public void initReqAndRep(HttpServletRequest request, HttpServletResponse response) {
        currentRequest.set(request);
        currentResponse.set(response);
        currentSession.set(request.getSession());
        setLogLevel(request);

    }

    /**
     * 设置日志级别的处理
     * @param request
     */
    public void setLogLevel(HttpServletRequest request){
        final Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            if (LOGGER_LEVEL.equalsIgnoreCase(key)){
                String value = request.getHeader(key);
                updateLogLevel(value);
                break;
            }


        }
    }

    /**
     * 获取当前线程安全的request
     * @return
     */
    public HttpServletRequest request() {
        return (HttpServletRequest) currentRequest.get();
    }
    /**
     * 获取当前的线程安全的response
     * @return
     */
    public HttpServletResponse response() {
        return (HttpServletResponse) currentResponse.get();
    }

    /**
     * 获取当前线程安全的session
     * @return
     */
    public HttpSession session() {
        return (HttpSession) currentSession.get();
    }
    /**
     *  set level every log level
     *  final Enumeration<Logger> logs = LogManager.getCurrentLoggers();
        while (logs.hasMoreElements()) {
        final Logger logger = logs.nextElement();
        // 给log4j对象设置级别  
        logger.setLevel(resultLevel);
        }
     * @param value
     * @return
     */

    public void updateLogLevel(String value){
        final Level level = LogManager.getRootLogger().getLevel();
        String levelStr = level.toString();
        if (levelStr.equals(value)) {
            LOGGER.info("日志级别不用改变");
        }
        final Level resultLevel = Level.toLevel(value);
        // 设置根日志级别  
        LogManager.getRootLogger().setLevel(resultLevel);
        // 获取配置文件中的所有log4j对象
       LOGGER.info("logger set success {} ... ",value);
    }

    /**
     * 初始化时间日期解决函数
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        binder.registerCustomEditor(Date.class, new SevenCustomDateEditor(true));
    }

}
